package com.dingdang.util;


import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author jiangrongtao 图片验证码
 */
public class VerificationCodeUtil {
    public static final String RANDOMCODEKEY = "RANDOMVALIDATECODEKEY";//放到session中的key
    private static List<Color> colors;
    static{
        colors=new ArrayList<>();
        colors.add(Color.CYAN);
        colors.add(Color.yellow);
        colors.add(Color.PINK);
        colors.add(Color.green);
    }
    /**
     * 1、绘制图片 2、给图片上随机绘制文字 3、随机绘制干扰线4、将图片绘制到浏览器
     * @param response HttpServletResponse
     * @param width  图片宽度
     * @param height 图片高度
     * @param fontNum 数字个数
     * @return 返回随机生成的验证码
     */
    public static String drawVerificationCode(HttpServletRequest request, HttpServletResponse response, int width, int height, int fontNum) {

        HttpSession session = request.getSession();
        /**
         * 生成图片
         */
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);

        // 绘制文字
        Graphics2D graphics2d = bufferedImage.createGraphics();
        graphics2d.setFont(new Font("华文行楷", Font.ITALIC | Font.BOLD, 20));// 设置字体样式

        String words = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz23456789";
        StringBuilder sb=new StringBuilder();
        // 随机取四个值
        Random random = new Random();
        for (int i = 1; i <= fontNum; i++) {
            char ch = words.charAt(random.nextInt(words.length()));
            graphics2d.setColor(getColor(random));// 设置字体颜色
            graphics2d.drawString(ch + "", (width/fontNum)*i-30, height/2+10);
            sb.append(ch);
        }
        //将生成的随机字符串保存到session中
        session.removeAttribute(RANDOMCODEKEY);
        session.setAttribute(RANDOMCODEKEY, sb.toString());
        //绘制干扰线
        for (int i = 0; i <5; i++) {
            graphics2d.setColor(getColor(random));
            int x1=random.nextInt(width);
            int x2=random.nextInt(width);
            int y1=random.nextInt(height);
            int y2=random.nextInt(height);
            graphics2d.drawLine(x1, y1, x2, y2);
        }

        try {
            ImageIO.write(bufferedImage, "jpg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * 随机获取一种颜色
     * @param random
     * @return Color
     */
    private static Color getColor(Random random){

        return random==null?null:colors.get(random.nextInt(4));
    }
}

